<?php
namespace app\admin\controller;

use app\admin\model\Accesses as AccessesModel;
use houdunwang\arr\Arr;
use think\Request;
use think\Config;
use think\Cache;
use think\Validate;

class Accesses extends Base
{
	/*
	 *	资讯列表
	*/
	public function index()
	{
		$data = AccessesModel::all();
		$list = Arr::tree($data, 'name', $fieldPri = 'id', $fieldPid = 'pid');

		// dd($list);
		$menu = self::getMenuArr();

		return view('index', compact('list', 'menu'));
	}

	/*
	 *	添加权限
	*/
	public function add()
	{

		if(Request::instance()->isPost()){
			$data = $this->request->param();
			// dd($data);
	        $validate = new Validate([
	            ['name', 'require', '请输入权限名称'],
	            ['sign', 'require', '请输入权限节点'],
	            ['sort', 'require', '请输入排序'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }

	        $res = AccessesModel::create([
	        	'name' => $data['name'],
	        	'sign' => $data['sign'],
	        	'pid' => $data['pid'],
	        	'sort' => $data['sort'],
	        ]);

	        if(!$res){
	        	return error('添加失败');
	        }
	        logger(2, '添加权限节点：'.$data['name']);

	        return success(['url'=>"/admin/accesses/index"], '添加成功');
		}

		$categroy = AccessesModel::where('pid', 0)->order('sort ASC')->field('id, name')->select();
		$menu = self::getMenuArr();

		return view('add', compact('categroy', 'menu'));
	}

	/*
	 *	编辑权限
	*/
	public function edit()
	{
		$id = $this->request->param('id');
		$detail = AccessesModel::find($id);

		if(Request::instance()->isPost()){
			$data = $this->request->param();
			// dd($data);
	        $validate = new Validate([
	            ['name', 'require', '请输入权限名称'],
	            ['sign', 'require', '请输入权限节点'],
	            ['sort', 'require', '请输入排序'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }

	        $res = AccessesModel::where('id', $data['id'])->update($data);

	        if($res || $res !== false){
	        	logger(2, '编辑权限节点：'.$data['name']);
	        	return success(['url'=>"/admin/accesses/index"], '更新成功');
	        }
	        
	        return error('添加失败');
		}

		$categroy = AccessesModel::where('pid', 0)->order('sort ASC')->field('id, name')->select();
		$menu = self::getMenuArr();

		return view('edit', compact('categroy', 'detail', 'menu'));
	}

	/*
	 *	删除权限
	*/
	public function del()
	{
		$id = $this->request->param('id');
		if(empty($id) || $id == ''){
			return error('请传要删除的ID');
		}

		$count = AccessesModel::where('pid', $id)->count();
		if($count){

			return error('请先删除子权限');
		}

		$res = AccessesModel::find($id);

		if(!$res){
			return error('数据不存在或被删除');
		}
		logger(2, '删除权限节点：'.$res['name']);

		$res->delete();

		return success(1, '删除成功');

	}
}
